<?php
namespace common\components\services\goods;
/*
 * 商品修改独立方法
 * */
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Brand;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use common\models\datas\TypeBrand;
use frontend\models\datas\Arrangement;
use frontend\models\datas\ClassLesson;
use frontend\models\datas\ClassroomAttr;
use frontend\models\datas\Course;
use frontend\models\datas\Teacher;
use yii\data\Pagination;
use yii\helpers\Json;
use frontend\models\datas\ClassManage;
use frontend\models\datas\Goods;
use frontend\models\datas\GoodsAttr;
use frontend\models\datas\Mechanic;
use yii\base\Action;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

class UpdateAction extends Action{
    //商品通用字段和所属类型特有的扩展字段于此视图中显示
    public $default_url='@common/components/services/goods/defaultview.php';

    /*
     * 开发思路
     * 1. 获取传入商品的id获得该商品模型
     * 2. 列出排课列表，对现在对应的课程有勾勾选中
     * 3. 其他选中默认，前端页面就参考着或者直接调用DefaultView.php了
     */
    public $type;

    public function run(){
        if(\Yii::$app->request->get('id')==null){
            throw new BadRequestHttpException(\Yii::t('frontend','商品id为空'));
        }
        $goodid = \Yii::$app->request->get('id');
        $good = Goods::findOne($goodid);
        $good->scenario = 'update';
        $attr = GoodsAttr::find()->where(['obj_type'=>'suitable_age','goods_id'=>$goodid])->one();
        if($attr != null){
            $arrGae = substr($attr->value,1,-1);
            $arr = explode(',',$arrGae);
            $good->min_age  = $arr[0];
            if(count($arr) == 1){
                $good->max_age  = $arr[0];

            }else{
                $good->max_age  = $arr[count($arr)-1];
            }
        }
        $attrregion = GoodsAttr::find()->where(['obj_type'=>'region','goods_id'=>$goodid])->one();
        if($attrregion){
            $good->region = $attrregion->value;
        }
        $is_update = false;
        $classmanage = ClassManage::find()->where(['associate_id'=>$good->id,'status'=>1])->one();
        if($classmanage != null){
            $lesson = ClassLesson::find()->where(['class_id'=>$classmanage->class_id,'lesson'=>2])->andWhere(['<=','class_date',time()])->one();
            if($lesson != null){
                $is_update = true;
            }
        }

        $mechanic = $this->getMechanic();
        if(\Yii::$app->request->get('type_id') == null){
            $this->type = $good->type_id;
        }else{
            $this->type = \Yii::$app->request->get('type_id');
        }

        $tree=$this->getCategory($this->type);//分类列表
        $brand = $this->getTypeBrand($this->type);//品牌
        //现在只考虑了课程的，后期要考虑其他类型的商品管理
        $attribute = Fun::getAttribute($this->type,$goodid);//获取扩展属性
        //ajax验证
        if(\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $good->load(\Yii::$app->request->post())){
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($good);
        }
        if ($good->load(\Yii::$app->request->post())&&$good->validate()) {

            if($good->save(false)){
                if (!empty($good->min_age) && !empty($good->max_age)) {
                    $str = ',';
                    $arr = range($good->min_age, $good->max_age);
                    if (count($arr) == 1) {
                        $str .= $arr[0] . ',';
                    } else {
                        foreach ($arr as $age) {
                            $str .= $age . ',';
                        }
                    }
                    if($attr != null){
                        $attr->value = $str;
                        $attr->save(false);
                    }else {
                        $goodsAttr = new GoodsAttr();
                        $goodsAttr->goods_id = $good->id;
                        $goodsAttr->name = '适合年龄段';
                        $goodsAttr->value = $str;
                        $goodsAttr->obj_type = 'suitable_age';
                        $goodsAttr->save(false);
                    }
                }
                if(!empty($good->region)){
                    if($attrregion !=null){
                        $attrregion->value = $good->region;
                        $attrregion->save(false);
                    }else{
                        $goodsRegion = new GoodsAttr();
                        $goodsRegion->goods_id = $good->id;
                        $goodsRegion->name = '地域';
                        $goodsRegion->value = $good->region;
                        $goodsRegion->obj_type = 'region';
                        $goodsRegion->save(false);
                    }
                }
                return $this->controller->redirectMessage('修改成功',Fun::url(['goodscourse/index','type_id'=>1]));
            }


        }else{
            \Yii::error('更新商品信息失败，验证错误信息：');
            \Yii::error($good->getErrors());
        }
        return $this->controller->render('update',['model'=>$good,'tree'=>$tree,'brand'=>$brand,'mechanic'=>$mechanic,'attribute'=>$attribute,'default'=>\Yii::$app->view->render($this->default_url,['model'=>$good,'tree'=>$tree,'brand'=>$brand,'mechanic'=>$mechanic,'attribute'=>$attribute,'type_id'=>$this->type,'is_update'=>$is_update])]);
    }

    //课程更改
    public function updateGood($model,$postdata){
        if($model == null){
            throw new NotFoundHttpException(\Yii::t('frontend', '修改商品不存在'));
        }
        //课程和消费商品通用都要更改的字段
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            if($this->type == 1){//课程类型的商品
                //更改课程多余模块属性
                if($model->is_shelve==1){
                    $model->up_at=$model->up_at==0?time():$model->up_at;
                    $is_class_manage=ClassManage::findOne(['is_old'=>0,'associate_id'=>$model->id]);
                    if($is_class_manage==null){
                        $goods_attr=GoodsAttr::findOne(['goods_id'=>$model->id,'obj_type'=>'is_booking']);
                        $class_manage=new ClassManage();
                        $class_manage->class_code='c'.time();
                        $class_manage->is_book=$goods_attr==null?'':$goods_attr->value;
                        $class_manage->is_old=0;
                        $class_manage->associate_id=$model->id;
                        $class_manage->mechanic_id=$model->mechanic_id;
                        $class_manage->save(false);
                    }
                }else{
                    $model->down_at=$model->down_at==0?time():$model->down_at;
                }

                if($model->save(false)){//更新成功了goods，继续更新扩展属性模板
                    $attribute = isset($postdata['attribute'])?$postdata['attribute']:null;
                    if(!empty($postdata['attr_value'])){
                        foreach($postdata['attr_value'] as $k=>$v){
                            $goodattr = GoodsAttr::findOne(['goods_id'=>$model->id,'attribute_id'=>$k,'obj_type'=>'attribute']);//,'obj_type'=>'attribute' 库表中有的是course，有的是attribute，等明确了这个字段再添加修改
                            if(!empty($goodattr)){
                                $goodattr->value = $v;
                                $goodattr->name = $attribute[$k];
                                $goodattr->save(false);
                            }else{
                                if(!empty($v)) {
                                    $goodattrnew = new GoodsAttr(['goods_id' => $model->id, 'name' => $attribute[$k], 'attribute_id' => $k, 'value' => $v, 'obj_type' => 'attribute']);
                                    $goodattrnew->save(false);
                                }
                            }
                        }
                    }
                    $transaction->commit();
                    $url = ['goodscourse/index','type_id'=>1];
                    return $this->controller->redirectMessage('修改成功',Fun::url($url));//不知为何这个redirectMessage不可用
                }else{
                    $transaction->rollBack();
                    \Yii::error('更新失败');
                    return $this->controller->redirectMessage('修改失败',Url::previous());
                }
            }elseif($this->type != 3){//不是舞台表演类型的商品，后期加上了这个舞台表演商品的功能，直接else就是普通商品了
                //普通商品
                $modelorigin = Goods::findOne($model->id);
                if(!empty($postdata['Goods']['imageList'])){
                    $imagelist = $postdata['Goods']['imageList'];
                    $imagelist_arr = [];
                    if(!empty($imagelist)){
                        $imagelist_arr = explode('#|#',$imagelist);
                    }
                    if(!empty($postdata['Goods']['defaulturl'])&&in_array($postdata['Goods']['defaulturl'],$imagelist_arr)){
                        $model->picture = $postdata['Goods']['defaulturl'];
                    }else{
                        if(count($imagelist_arr)>0){
                            $model->picture = $imagelist_arr[0];//上传的列表第一个作为展示的默认图
                        }else{
                            $model->picture = '';
                        }
                    }
                }else{
                    $model->picture = '';
                }

                if($modelorigin->is_shelve==0 && $postdata['Goods']['is_shelve']==1){
                    $model->up_at = time();
                }elseif($modelorigin->is_shelve==1 && $postdata['Goods']['is_shelve']==0){
                    $model->down_at = time();
                }
                if($model->save(false)){//更新成功，更新扩展属性
                    if(!empty($postdata['attr_value'])){
                        $attribute = isset($postdata['attribute'])?$postdata['attribute']:null;
                        foreach($postdata['attr_value'] as $k=>$v){
                            /*
                             * 遍历获取填写的扩展属性，到库表中查该model该属性id是否已经存在了值了，如果存在了，则更新其value
                             * 如果不存在，则执行插入操作
                             */
                            $goodattr = GoodsAttr::findOne(['goods_id'=>$model->id,'attribute_id'=>$k]);
                            if($goodattr == null){//执行插入操作
                                $goodattrnew = new GoodsAttr(['goods_id'=>$model->id,'name'=>$attribute[$k],'attribute_id'=>$k,'value'=>$v,'obj_type'=>'attribute']);
                                $goodattrnew->save(false);
                            }else{//执行更新操作
                                if(!empty($v)) {
                                    $goodattr->value = $v;
                                    $goodattr->name = $attribute[$k];
                                    $goodattr->save(false);
                                }
                            }
                        }
                    }
                    $transaction->commit();
                    $url = ['goodsproduct/index','type_id'=>$this->type];//后期消费品创建成功要改为消费品的url链接
                    //return \Yii::$app->controller->redirect(Fun::url(['goodsproduct/index','type_id'=>$this->type]));
                    return $this->controller->redirectMessage('更新成功',Fun::url($url));//不知为何这个redirectMessage不可用
                }else{
                    $transaction->rollBack();
                    \Yii::error('更新失败');
                    return $this->controller->redirectMessage('更新失败',Url::previous());
                }
            }
        }catch (Exception $e){
            $transaction->rollBack();
            //后期做完测
            return $this->controller->redirectMessage('更新失败',Url::previous());
        }
    }
    //获取分类树
    public function getCategory($type_id){
        $site_id=Fun::getSiteId();
        //在当前分店中能够显示的分类列出来
        $cate_attr=CateAttr::find()->select(['cat_id'])->where(['or',['mobile_is_show'=>1],['pc_is_show'=>1]])->andWhere(['site_id'=>$site_id])->orderBy('pc_sort asc')->column();
        $category=Cate::find()->indexBy('id')->where(['in','id',$cate_attr])->andWhere(['type_id'=>$type_id])->asArray()->all();
        $tree = (new Tree($category))->get_tree_select();//得到树形列表供用户选择
        return  $tree;
    }

    //获得类型品牌
    public function getTypeBrand($type_id){
        $brand_id = TypeBrand::find()->select(['brand_id'])->where(['type_id'=>$type_id])->column();
        $brand = Brand::find()->where(['in','id',$brand_id])->all();
        $result = ArrayHelper::map($brand, 'id', 'name');
        return $result;
    }

    //获取机构列表
    public function getMechanic(){
        $mids = Fun::getMechanicIds();
        $mechanicModel=Mechanic::find()->where(['site_id'=>Fun::getSiteId(),'is_delete'=>0,'status'=>1]);
        if($mids){
            $mechanicModel->andWhere(['id'=>$mids]);
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        $tree_mechanic=(new Tree($mechanic))->get_tree_select();
        //$result = ArrayHelper::map($mechanic, 'id', 'name');
        return  $tree_mechanic;
    }
}
?>
